import { createRouter, createWebHashHistory } from "vue-router";
import Layout from '@/layout/index.vue'
import PageFrame from '@/layout/components/PageFrame.vue'
import store from "../store";
import { getMenuTree, getUserInfo } from "@/apis/sysUser";

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Layout,
        children: [
            {
                path: 'login',
                name: 'Login',
                component: () => import('@/views/login/index.vue'),
            },
            {
                path: '404',
                name: 'NotFound',
                component: () => import('@/views/404.vue')
            },
            {
                path: 'personal',
                name: 'Personal',
                meta: {
                    requireAuth: true,
                },
                component: () => import('@/views/personal/index.vue'),
                children: [
                    {
                        path: 'message',
                        name: 'PersonalMessage',
                        meta: {
                            requireAuth: true,
                        },
                        component: () => import('@/views/personal/Message.vue')
                    }
                ]
            },
            // {
            //     name: "App",
            //     path: "/app",
            //     children: [
                    
            //     ]
            // },
            // {
            //     name: "SysUser",
            //     path: "/sys/user",
            //     component: () => import("@/views/sys/SysUser.vue"),
            // },
            // {
            //     name: "Role",
            //     path: "/sys/role",
            //     component: () => import("@/views/sys/Role.vue"),
            // },
            // {
            //     name: "Permission",
            //     path: "/sys/permission",
            //     component: () => import("@/views/sys/Permission.vue"),
            // },
            // {
            //     name: "LogsVisitor",
            //     path: "/logs/visitor",
            //     component: () => import("@/views/logs/Visitor.vue"),
            // },
            // {
            //     name: "LogsOperation",
            //     path: "/logs/operation",
            //     component: () => import("@/views/logs/Operation.vue"),
            // }
        ]
    },
    // {
    //     path: '/:pathMatch(.*)*',
    //     name: '404',
    //     redirect: '/404',
    //     component: () => import('@/views/404.vue')
    // }
]

const route404 = {
    path: "/:pathMatch(.*)*",
    name: "404",
    redirect: "/404"
}

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {    
    const isLogin = store.getters["user/isLogin"]
    
    if (to.path === "/login") {
        if (isLogin) {
            return next({name: "Home"})
        }
        return next()
    }

    if (to.meta.requireAuth && !isLogin) {
        return next({name: "Login"})     
    }
    
    if (isLogin) {
        await addDynamic()

        if (!to.name && hasRoute(to)) {
            return next({ ...to , replace: true})
        }

        if (to.path === "/" && store.state.firstRoute) {
            next({name: store.state.firstRoute.name})
        }
    }

    next()
})

function hasRoute(to) {
    const item = router.getRoutes().find((item) => item.path === to.path)    
    return !!item
}

async function addDynamic() {
    // 如果已经添加过则直接返回    
    if (store.state.routeLoaded) {
        return
    }    

    return getMenuTree().then((res) => {
        if (res.data && res.data.length) {
            addDynamicRoutes(res.data)
        }
        // 手动添加404重定向
        router.addRoute(route404)
        // 保存路由加载状态
        store.commit("setRouteLoaded", true)
        // 保存菜单树
        store.commit("setMenuTree", res.data)
    })
}

// 动态引入所有的vue组件
const modules = import.meta.glob("../views/**/*.vue")

// 添加动态路由
function addDynamicRoutes(data, parent) {
    data.forEach((item, i) => {
        // 定义路由
        const route = {
            path: item.path,
            name: item.name,
            meta: {
                label: item.label,
                icon: item.icon,
            },
            children: []
        }

        // 如果有父菜单
        if (parent) {
            // 且不是根菜单
            if (item.parentId !== 0) {
                // 解析组件路径
                // const compParr = item.path.replace("/", "").split("/")
                // const l = compParr.length - 1
                // const compPath = compParr
                //     .map((v, i) => {
                //         return i === l ? v.replace(/\w/, (L) => L.toUpperCase()) + ".vue" : v
                //     })
                //     .join("/")

                // route.path = compParr[l]
                // 设置组件
                route.component = modules[`../views/${item.url}.vue`]                       
                // 添加到父级菜单
                parent.children.push(route)    
            }
        } else {
            // 不存在父菜单
            // 如果有子菜单
            if (item.children && item.children.length) {
                // 默认重定向到第一个子菜单
                route.redirect = item.children[0].path
                // 递归添加子菜单
                addDynamicRoutes(item.children, route)
            }

            // 设置组件
            route.component = PageFrame

            // 如果是第一个添加的组件，则设置为第一个重定向的路由
            if (i === 0) {
                store.commit("setFirstRoute", route)
            }
            // 添加路由到Home下
            router.addRoute("Home", route)
        }
    })
}

export default router